import React, { useEffect } from "react";
import { useSelector } from "react-redux";
import { RootState } from "@/store";
import { useNavigate } from "react-router-dom";
import { message } from "antd";

interface PrivateRouterProps {
  children: React.ReactNode;
}

const PrivateRouter: React.FC<PrivateRouterProps> = ({ children }) => {
  const navigate = useNavigate();
  const isLogin = useSelector(
    (state: RootState) => state.UserInfoStore.shortToken
  );

  console.log("ReivateRouter is Rendering");

  useEffect(() => {
    if (!isLogin) {
      // 跳转到登录页面
      message.warning("请先登录，正在前往登录页面", 1.5, () => {
        navigate("/login");
      });
    }
  }, [isLogin, navigate]);

  if (isLogin === undefined) {
    // 处理首次加载时的延迟
    return <div>Loading...</div>;
  }

  return isLogin ? <>{children}</> : null;
};

export default PrivateRouter;
